
import * as Blockly from 'blockly/core'
import { getAllComponentList } from '../utils/component'
import { getContextText } from '../utils/block'
const selectData = ['hlSelect', 'hlCheckbox', 'hlDepartment', 'hlPersonnel', 'hlRadio', 'hlTree' ]
const selectedType = [ 'hlTableList']
const selectdValueTypes = ['hlMindmap']
const selectNode = ['hlProcess']
const allSelectTypes = [...selectData, ...selectedType, ...selectdValueTypes, ...selectNode]
Blockly.Extensions.register('dynamic_select_component_extension',
  function () {
    var that = this
    const list = getAllComponentList()
    const comList = list.filter(item => allSelectTypes.includes(item.tagName))
    const validator = function (newValue) {
      const compVar = that.getFieldValue('Component') // 组件的key
      const com = comList.find(item => item.key === compVar)
      if (!com) return
      const comType = com.tagName
      if (selectNode.includes(comType) || selectdValueTypes.includes(comType)) {
        that.setOutput(true, 'Object')
      } else {
        that.setOutput(true, 'Array')
      }
    }
    const dropdown = new Blockly.FieldDropdown(
      function () {
        var options = []

        if (!comList.length) {
          options = [['没有数据', 'noData']]
          return options
        }
        for (var i = 0; i < comList.length; i++) {
          const com = comList[i]
          const label = (com?.modelName) ? (com?.__config?.label) : ''
          var dateString = com.name + label + '（' + com.key + '）'
          options.push([dateString, com.key])
        }
        return options
      })
    dropdown.setValidator(validator)
    this.getInput('COMPONENT_INPUT').appendField(dropdown, 'Component')
  })

// 1.--------获取组件实例------------
const componentSelectJson = {
  type: 'component_get_select_data',
  message0: '获取选中数据 %1',
  args0: [
    // 动态生成选项
    {
      'type': 'input_dummy',
      'name': 'COMPONENT_INPUT'
    }
  ],
  extensions: ['dynamic_select_component_extension'],
  output: null,
  style: 'action_blocks',
  tooltip: '',
  helpUrl: ''
}

// 创建积木
Blockly.Blocks['component_get_select_data'] = {
  init: function () {
    this.jsonInit(componentSelectJson)
  }
}

Blockly.JavaScript['component_get_select_data'] = function (block) {
  // todo  后面统一api
  const compVar = block.getFieldValue('Component')
  const context = getContextText(block, compVar)
  const code = `${context}.getComponent('${compVar}').dispatch('getSelectData')`
  return [code, Blockly.JavaScript.ORDER_ATOMIC]
}
